package com.zero.book.service;

import com.zero.book.entity.Book;

import java.io.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;

import static com.zero.book.message.MessageConstant.*;
import static com.zero.book.message.MessageConstant.DEVELOP_MODE_EXITED;
import static com.zero.book.utils.PrintUtil.*;
import static com.zero.book.service.SerialService.*;
import static com.zero.book.service.CRUDService.*;

public class DevelopService {

    /**
     * 开发模式
     */
    public static void DevelopMode(Scanner sc) {
        print(ENTER_PWD);
        if (sc.nextLine().equals("123456")) {
            print(DEVELOP_MODE);
            print(DEVELOP_MODE_ADD);
            print(DEVELOP_MODE_DELETE);
            print(DEVELOP_MODE_EXIT);
            switch (Integer.parseInt(sc.nextLine())) {
                case 1:
                    try {
                        fileToMap(new FileInputStream(new File("presuppose.txt")));
                    } catch (FileNotFoundException e) {
                        throw new RuntimeException(FILE_PATH_ERROR + "!");
                    }
                    print(DEVELOP_ADD_SUCCESS);
                    break;
                case 2:
                    try {
                        Map<Integer, Book> dataMap = new LinkedHashMap<>();
                        serialSaveService(dataMap);
                        print(DEVELOP_DELETE_SUCCESS);
                    } catch (Exception e) {
                        print(DEVELOP_DELETE_FAILURE);
                    }
                    break;
                case 3:
                    print(DEVELOP_MODE_EXITED);
                    break;
                default:
            }
        }
    }

    //
    public static void fileToMap(FileInputStream fis) {
        BufferedReader br = new BufferedReader(new InputStreamReader(fis));
        Map<Integer, Book> map = serialLoadService();
        try {
            String line_data = null;
            while ((line_data = br.readLine()) != null) {
                String[] properties = line_data.split(" ");
                Book book = Book.builder()
                        .title(properties[0])
                        .author(properties[1])
                        .price(Double.parseDouble(properties[2]))
                        .build();
                int key = SetCurKey(NO_TIPS_OPEN);
                map.put(key, book);
                serialSaveService(map, NO_TIPS_OPEN);
            }
            print(AUTO_SAVE_SUCCESS);
        } catch (IOException e) {
            throw new RuntimeException(AUTO_SAVE_FAILURE + "", e);
        }

    }
}
